import { getRandomKey, urlEncode } from '@/utils/utils';
import { reqGet } from '@/utils/request';
import apiConfig from '@/apiConfig';
import { message } from 'antd';
import { myFormatMessage } from '@/utils/localeUtils';

const authorObj = {
  login: {
    url: '/user/wxAuthor',
  },
  bind: {
    url: '/transformCode',
  },
};

export const getWxAuthorQR = (containerID, type = 'login', opt = {}) => {

  if (window.WxLogin && document.getElementById(containerID)) {
    if ('undefined' !== typeof NProgress) {
      NProgress.start();
      NProgress.set(0.3);
    }
    // 获取微信配置
    reqGet(apiConfig.getWecahtConf).then(rsp => {
      if ('undefined' !== typeof NProgress) {
        NProgress.done();
      }
      if (rsp && 200 === rsp.status && rsp.data) {
        const origin = rsp.data.redirect_host;
        const path = window.location.host === 'localhost' ? '/myjz' : window.location.pathname;
        let routePath = authorObj[type] ? authorObj[type].url : '';
        let queryStr = opt.query ? '?' + urlEncode(opt.query) : '';

        if ('' === routePath) {
          return `getWxAuthorQR：没有 ${type} 的微信授权类型`;
        }
        // console.log(origin+path+'#'+location.pathname);
        new window.WxLogin({
          // self_redirect: true,
          id: containerID,
          appid: rsp.data.appid,
          scope: 'snsapi_login',
          redirect_uri: encodeURIComponent(`${origin}${path}#${routePath}${queryStr}`),
          state: getRandomKey(),
          // style: '',
          // href: '',
          ...opt,
        });
      } else {
        // 获取微信配置失败
        message.error(myFormatMessage('tip.wxLogin.noConf'));
      }
    });
  }
};
